import { fetchProjectDetail, fetchWorkflow, listWorkflowExecutionRecord, listTask } from './api';
import yaml from 'yaml';

/**
 * @description: 数据处理
 * 2022/3/22 16:45
 * @author: zsjin
 */
export const getRecordData = async ({ projectId, workflowExecutionRecordId, baseUrl }: {
    projectId: string;
    workflowExecutionRecordId?: string;
    baseUrl: string;
}) => {
  const project = await fetchProjectDetail(projectId, baseUrl);
  const allRecords = await listWorkflowExecutionRecord(project.workflowRef, baseUrl);
  let record = allRecords.length === 0
    ? undefined
    : (
      workflowExecutionRecordId
        ? allRecords.find(item => item.id === workflowExecutionRecordId)
        : allRecords[0]
    );
  const { dslText, nodes } = await fetchWorkflow(
    record ? record.workflowRef : project.workflowRef,
    record ? record.workflowVersion : project.workflowVersion,
    baseUrl);
  const recordDsl = dslText;
  const nodeInfos = nodes
    .filter(({ metadata }) => metadata)
    .map(({ metadata }) => JSON.parse(metadata as string));
  if (!record) {
    const dsl = yaml.parse(recordDsl);
    const description = dsl.workflow?.description || dsl.pipeline?.description;
    record = {
      id: '',
      serialNo: 0,
      name: project.workflowName,
      workflowRef: project.workflowRef,
      workflowVersion: project.workflowVersion,
      description,
      startTime: '',
      status: '',
      triggerId: '',
      triggerType: project.triggerType,
    };
  }
  const taskRecords = !record.triggerId ? [] : await listTask(record.triggerId, baseUrl);
  return { project, allRecords, record, recordDsl, taskRecords, nodeInfos };
};